package com.itlxd.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itlxd.common.ThreadLocalUtils;
import com.itlxd.global.SysConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * @author: lixiaodong
 **/
@Slf4j
@Component
public class MybatisPlusHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        //创建时间
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        //修改时间
        this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
        //创建人
        this.strictInsertFill(metaObject, "createUser", () -> ThreadLocalUtils.getCurrentId(), Long.class);
        //修改人
        this.strictInsertFill(metaObject, "updateUser", () -> ThreadLocalUtils.getCurrentId(), Long.class);
        //默认密码123456
        this.strictInsertFill(metaObject, "password", () -> DigestUtils.md5DigestAsHex(SysConstants.DEFAULT_PASSWORD.getBytes()), String.class);
        //默认状态1
        this.strictInsertFill(metaObject, "status", () -> SysConstants.YES, Integer.class);
        //默认顺序0
        this.strictInsertFill(metaObject, "sort", () -> SysConstants.NUM_ZERO, Integer.class);
        //随机生成商品码
        this.strictInsertFill(metaObject, "code", () -> Integer.valueOf(((int) (Math.random()*100000000))).toString(), String.class);
        //下单的用户Id
        this.strictInsertFill(metaObject, "userId", () -> ThreadLocalUtils.getCurrentId(), Long.class);
        //下单时间
        this.strictInsertFill(metaObject, "orderTime", () -> LocalDateTime.now(), LocalDateTime.class);
        //结账时间
        this.strictInsertFill(metaObject, "checkoutTime", () -> LocalDateTime.now(), LocalDateTime.class);
        //默认性别为1
        this.strictInsertFill(metaObject, "sex", () -> SysConstants.MALE, Integer.class);
        //默认名为Customer
        this.strictInsertFill(metaObject, "name", () -> SysConstants.DEFAULT_NAME, String.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictUpdateFill(metaObject, "updateUser", () -> ThreadLocalUtils.getCurrentId(), Long.class);
    }
}
